function sendMsg(){
    var v = document.getElementById('sendInput').value;
    addSendMsgToResultBox(v);
    document.getElementById('sendInput').value="";

    sendQuestion(v);
}

function getUserName(){
    var userName = localStorage.getItem("AgCIM_Desktop_Doc.Usr");
    if (userName && userName.indexOf('@') > 0) {
      userName = userName.substring(0, userName.indexOf('@'));
    }
    else {
      userName = "未署名";
    }
    return userName;
}

function addSendMsgToResultBox(v){
    var div=document.createElement('div');
    div.className='userSendTextL1';
    div.innerHTML = `<div  class='userSendText' style='text-align: right;'><label >` + v +`</label></div>`
    var chatBox = document.getElementById('chatBox');
    chatBox.appendChild(div);

    chatBox.scrollTo(0, chatBox.scrollHeight)
}

function addResponeMsgToResulBox(v) {
    var contentVs = getContentAndReferences(v);

    var responseDiv = null;
    var existDiv = true;
    if (contentVs.uid) {
        responseDiv = document.getElementById(contentVs.uid);
    }
    if (responseDiv == null) {
        var div = document.createElement('div');
        div.className = 'userSendTextL1_response';
        responseDiv = div;
        responseDiv.id = contentVs.uid;
        existDiv = false;
    }
    else {
        existDiv = true;
    }

    var className = window.isMobile ? "userSendText2" :"userSendText2 limitWidth"
    if (!contentVs.ref) {
        responseDiv.innerHTML = `<div class='${className}'><label >` + marked(contentVs.content) + `</label></div>`
    }
    else {
        responseDiv.innerHTML = `<div class='${className}'><label >` + marked(contentVs.content) + `</label>` +
            `<div class="ref-button btn" onclick="showReference()">查看引用</div>` +
            `</div>`
    }
    var chatBox = document.getElementById('chatBox');
    if (existDiv == false)
        chatBox.appendChild(div);
    chatBox.scrollTo(0, chatBox.scrollHeight)
}
function EnterKey(event) {
    event = event || window.event;
    if (event.keyCode == 13) {
        sendMsg()
    }
}

function getAllTopic(){
    sendData("ChatGpt:GetAllTopic:null,desktop")
}
var chat_history=[];
var hasGetTopic = false;
var lastQuestion = null;

function sendQuestion(query){
    if (hasGetTopic==false){
        alert("尚未读取到话题组");
        return;
    }
    var selOption = document.getElementsByClassName('paperTypeStyle')[0];
    var topic = selOption.value;
    var b = {
        "paper_id": "[paper_id]",
        "query": query,
        "chat_history": chat_history,
        "arxiv_id": null
    }
    lastQuestion =query;
    sendData("ChatGpt:" + topic +":"+getUserName()+":"+JSON.stringify(b)+",desktop");
    document.getElementById('stateLabel').innerText="已发送，等待回复，一般需要10秒";
}

getAllTopic();

addHandler("ChatGpt",function(v){
    if (hasGetTopic==false){
        var vs = v.split(',');
        var selOption = document.getElementsByClassName('paperTypeStyle')[0];
        for (var i = 0; i < vs.length; i++) {
            var option = document.createElement('option');
            option.text = vs[i];
            selOption.appendChild(option)
        }
        hasGetTopic =true;
    }
    else{
        document.getElementById('stateLabel').innerText="完成"
        chat_history.push({
            "question": lastQuestion,
            "response": v
        })
        if (chat_history.length>3){
            chat_history.splice(0,1);
        }
        addResponeMsgToResulBox(v);
    }
})

var lastRefrenceContent="";
var isfirstInitReference=true;
function getContentAndReferences(v) {
    let uid =null;
    if (v.startsWith("UID=")) {
        var t1 = v.indexOf(",");
        uid = v.substring(0, t1);
        v = v.substring(t1 + 1);
    }
    var t=v.indexOf("<ref>")
    if (t < 0) {
        return { content:v, ref: null, uid }
    }
    var content=v.substring(0,t);
    var v2=v.substring(t+5);
    var v2Json=JSON.parse(v2);
    var paragraph_lis = v2Json.paragraph_list;
    lastRefrenceContent = paragraph_lis;
    return { content,ref: paragraph_lis, uid }
}
function firstInitReference(){
    // Get the popup element  
    var popup = document.getElementById("popup");

    // Get the close button element  
    var closeButton = document.getElementsByClassName("close-button")[0];

    // When the user clicks the close button, close the popup  
    closeButton.onclick = function () {
        popup.style.display = "none";
    }

    // When the user clicks anywhere outside of the popup, close it  
    window.onclick = function (event) {
        if (event.target == popup) {
            popup.style.display = "none";
        }
    }
}
function showReference(){
    if (isfirstInitReference){
        firstInitReference();
    }
    var popup = document.getElementById("popup");
    popup.style.display = "block";
    var pc=document.getElementsByClassName('popup-content')[0];
    for(var i=pc.children.length-1;i>0;i--){
        pc.children[i].remove();
    }
    for(var i=0;i<lastRefrenceContent.length;i++){
        var item = lastRefrenceContent[i];
        var divBlock=document.createElement('div');
        var content = marked(item.content);

        content = content.replace(/<img/g, '<br><img');
        content = content.replace(/<table>/g, '<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">');

        divBlock.innerHTML = '<h3 color="red">' + "引 " + (i + 1) 
            +"<span style='font-size:12px;color:#343775;padding-left:5px;padding-right:5px'>"
            +item.similarity.toFixed(2)+"</span> "+ item.title+"</h3>"+
            "<div style='font-size:13px;font-family:\"Noto Sans\";font-weight:200'>" + content +"</div>";
        pc.appendChild(divBlock);
    }
}